import {
  constantRoutes
} from '@/lib/router';

/**
 * Use meta.role to determine if the current user has permission
 * @param roles 权限列表
 * @param route 路由
 */
function hasPermission (haveRoter, route) {
  if (route.meta && route.meta.code) {
    if (route.meta.code.indexOf('>') > -1) {
      let _iclude = true;
      const _codes = route.meta.code.split('>');
      for (const i in _codes) {
        if (!haveRoter.includes(_codes[i])) {
          _iclude = false;
          break;
        }
      }
      return _iclude;
    } else {
      return haveRoter.some(code => {
        if (route.meta.code === code) {
          return true;
        } else {
          return false;
        }
      });
    }
  } else {
    return false;
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes (routes, haveRoter, rootPath, tenantId) {
  const res = [];
  routes.forEach(route => {
    const tmp = {
      ...route
    };
    const _path = tmp.path ? (/^\//.test(tmp.path) ? tmp.path.substring(1) : tmp.path) : '';
    rootPath = rootPath || '';
    const _rootPath = rootPath + '/' + _path;
    if (hasPermission(haveRoter, tmp)) {
      if (tmp.children) {
        if (tmp.children.length > 0) {
          setRedirect(tmp, _rootPath, tenantId);
        }
      }
      res.push(tmp);
      // } else if (tmp.meta && tmp.meta.code) {
      //   console.log('该路由需要权限' + route.meta.code + '，没有该权限');
    } else if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children, haveRoter, _rootPath, tenantId);
      if (tmp.children.length > 0) {
        setRedirect(tmp, _rootPath, tenantId);
        res.push(tmp);
      }
    }
  });

  return res;
}
// 设置redirect
function setRedirect (tmp, _rootPath, tenantId) {
  if (Object.keys(tmp).includes('redirect')) {
    let _paths = '';
    let _names = '';
    for (const i in tmp.children) {
      const item = tmp.children[i];
      if (!item.hidden) {
        _names = item.name ? item.name : '';
        _paths = item.path ? item.path : '';
        _paths = _paths ? (_paths.substring(0, 1) === '/' ? _paths : ('/' + _paths)) : '';
        break;
      }
    }
    if (!_names) {
      tmp.redirect = _rootPath + _paths;
      tmp.redirect = (/^\/\//.test(tmp.redirect) ? tmp.redirect.substring(1) : tmp.redirect);
    } else {
      tmp.redirect = {
        name: _names,
        params: {
          tenantId: 't__' + tenantId
        }
      };
    }
  }
}

/**
 * 设置路由的徽标
 * @param {array} routers 路由列表
 * @param {object} aData 徽标数据  { [code]: [value]}
 */
function setRouterBadge (routers, aData) {
  routers.forEach(route => {
    filterCodeToValue(route, aData);
    if (route.children) {
      setRouterBadge(route.children, aData);
    }
  });
}
/**
 * 判断设置值
 * @param {object} routers 路由
 * @param {object} aData 徽标数据  { [code]: [value]}
 */
function filterCodeToValue (routers, aData) {
  if (routers.meta && routers.meta.code) {
    if (Object.keys(aData).includes(routers.meta.code)) {
      routers.meta.badge = aData[routers.meta.code];
    }
  }
}

/**
 * 设置路由的meta中的值
 * @param {array} routers 路由列表
 * @param {object} aData 变化数据数据  { [code]: [value]}
 * @param {string} metaCode 控制节点 及 值 {code: '',valueCode: ''}
 */
function setRouterMetaByKey (routers, aData, metaCode) {
  routers.forEach(route => {
    filterMeatKeyCodeToValue(route, aData, metaCode);
    if (route.children) {
      setRouterMetaByKey(route.children, aData, metaCode);
    }
  });
}

/**
 * 设置路由meta中对应的值
 * @param {object} routers 路由
 * @param {object} aData 变化数据数据  { [code]: [value]}
 * @param {string} metaCode 控制节点 及 值 {code: '',valueCode: ''}
 */
function filterMeatKeyCodeToValue (routers, aData, metaCode) {
  const { code, valueCode } = metaCode;
  // console.log(code);
  // console.log(valueCode);
  if (routers.meta && routers.meta[code]) {
    if (Object.keys(aData).includes(routers.meta[code])) {
      // console.log('haskeys+++++++++++++', routers.meta[code]);
      routers.meta[valueCode] = aData[routers.meta[code]];
    }
  }
}

const state = {
  routes: [],
  addRoutes: [],
  storeId: ''
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
  SET_STOREID: (state, id) => {
    state.storeId = id;
  }
};

const actions = {
  generateRoutes ({
    commit
  }, aData) {
    return new Promise(resolve => {
      console.log('处理router参数----', aData);
      const routers = aData.routers;
      const extendRouterList = aData.extendRouterList ? aData.extendRouterList : [];
      const _extData = extendRouterList.length > 0 ? extendRouterList[0].children : [];
      const tenantId = aData.tenantId;
      console.log(aData);
      const accessedRoutes = window.location.pathname === '/hall.html' ? aData.extendRouterList : filterAsyncRoutes(_extData, routers, '/t__' + tenantId, tenantId);
      // let hasRoot = false;
      // accessedRoutes.forEach(route => {
      //   if (route.path === '/') {
      //     hasRoot = true;
      //   }
      // });
      // if (!hasRoot) {
      //   accessedRoutes.push({
      //     path: '/',
      //     redirect: accessedRoutes.length > 0 ? accessedRoutes[0].name ? {
      //       name: accessedRoutes[0].name
      //     } : accessedRoutes[0].path : '',
      //     hidden: true
      //   });
      // }
      let rebackRouters = accessedRoutes;
      const _accessedRoutes = JSON.parse(JSON.stringify(accessedRoutes));
      console.log('处理后路由', _accessedRoutes);
      if (extendRouterList.length > 0) {
        // rebackRouters = [{ path: extendRouterList[0].path, name: extendRouterList[0].name, children: [...accessedRoutes], redirect: accessedRoutes[0].name ? { name: accessedRoutes[0].name } : accessedRoutes[0].path }];
        rebackRouters = [...extendRouterList];
        if (window.location.pathname !== '/hall.html') {
          rebackRouters[0].children = [...accessedRoutes];
          rebackRouters[0].redirect = accessedRoutes[0].name ? {
            name: accessedRoutes[0].name
          } : accessedRoutes[0].path !== '*' ? (rebackRouters[0].path + '/' + accessedRoutes[0].path) : '';
          _accessedRoutes.map(item => {
            if (item.path.substring(0, 1) !== '/') {
              item.path = '/t__' + tenantId + '/' + item.path;
            }
          });
        } else {
          rebackRouters[0].redirect = accessedRoutes[0].children[0].name ? {
            name: accessedRoutes[0].children[0].name
          } : accessedRoutes[0].children[0].path !== '*' ? (rebackRouters[0].path + '/' + accessedRoutes[0].children[0].path) : '';
        }
      }
      commit('SET_ROUTES', _accessedRoutes);
      console.log(rebackRouters);
      resolve(rebackRouters);
    });
  },
  addRoutes ({
    commit
  }, routes) {
    commit('SET_ROUTES', routes);
  },
  setRouterBadge ({
    commit,
    state
  }, aData) {
    const routers = state.routes.concat();
    setRouterBadge(routers, aData);
    commit('SET_ROUTES', routers);
  },
  // 设置修改路由是否disable
  setRouterDisable ({ commit, state }, aData) {
    const routers = state.routes.concat();
    console.log(routers);
    setRouterMetaByKey(routers, aData, { code: 'disableCode', valueCode: 'diablesValue' });
    commit('SET_ROUTES', routers);
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
